Data File Handling | Computer Science Class 12 | Random Access in Python |Read and Write Method | Python | Board exam 2025 | Notes | Study Material

 Random Access in Python

Accessing and Manipulating Location of file Pointer

    Read    tell()

    Write seek()

Text file & Binary File

The tell() function  -->Read

    The tell() function returns the current position of the file pointer in the file. It is used as per the following Syntax

Syntax

    <file_object>.tell()

    Where file_object is the file handle of the open file.

Program:

    Fh=open("text.txt","r")

    print("Initially file_pointer position is at", fh.tell())

    print("3 bytes read are:",fh.read(3))

    print("Initially file_pointer position is at", fh.tell())

Output:


 
Mark.txt





 
The seek() Function

    The seek() function changes the position of the file by placing at the specific position in the open file.

 Syntax:

    <File_object>.seek(offset,[mode])

Where

    Offset   is a number specifying number of bytes.

    Mode    is a number 0 or 1 or 2 signifying

  •    0 for beginning of file (to move file - pointer w.r.t beginning of file ) it is default position (i.e when no mode is specified)
  •     1 for current position   of file-pointer(to move file-pointer w.r.t current position of it)
  •     2 for end of file(to move file-pointer w.r.t end of the file)

File Object

    Is the handle of open file.

Program:

    fh=open("text.txt","r") #will place the file pointer at 30 th byte from the beginning of the file(default)

  •     fh.seek(30) # will place the file pointer at 30th bytes ahead of current file pointer position (mode=1)
  •    fh.seek(30,1) # will place the file pointer at 30 bytes behind (backward direction) from -end-of-file (mode=2)
  •      fh.seek(-30,2) 

NOTE: Backward  movement of the file -pointer is not possible from the beginning of the file (BOF)

    Forward movement of file -pointer is not possible from the end of file(EOF)

 

Post a Comment

0 Comments